package com.zhiche.wms.admin.controller.itf;

import com.baomidou.mybatisplus.plugins.Page;
import com.lisa.json.JSONUtil;
import com.lisa.syslog.SysLogUtil;
import com.lisa.syslog.model.SysLogDataPo;
import com.zhiche.wms.configuration.MyConfigurationProperties;
import com.zhiche.wms.core.supports.BaseException;
import com.zhiche.wms.core.supports.RestfulResponse;
import com.zhiche.wms.core.supports.enums.RedisLogTypeEnum;
import com.zhiche.wms.core.supports.enums.SystemEnum;
import com.zhiche.wms.core.utils.SnowFlakeId;
import com.zhiche.wms.domain.model.log.ItfImplogHeader;
import com.zhiche.wms.domain.model.otm.OtmOrderRelease;
import com.zhiche.wms.domain.model.otm.OtmReleaseOtmDTO;
import com.zhiche.wms.domain.model.otm.OtmUpdateShipWmsDate;
import com.zhiche.wms.domain.model.otm.ShipmentInfo;
import com.zhiche.wms.dto.opbaas.resultdto.ReleaseDTO;
import com.zhiche.wms.service.dto.ShipmentDTO;
import com.zhiche.wms.service.log.IItfImplogHeaderService;
import com.zhiche.wms.service.log.ImportShipment;
import com.zhiche.wms.service.otm.IOtmShipmentService;
import com.zhiche.wms.service.redislog.LogDataPo;
import com.zhiche.wms.service.utils.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by zhaoguixin on 2018/6/12.
 */
@RestController
@RequestMapping(value = "/shipment")
public class ShipmentController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ShipmentController.class);

    @Autowired
    private SnowFlakeId snowFlakeId;
    @Autowired
    private IItfImplogHeaderService iItfImplogHeaderService;
    @Autowired
    private IOtmShipmentService iOtmShipmentService;

    @Autowired
    private ImportShipment importShipment;

    @Autowired
    private MyConfigurationProperties properties;

    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public RestfulResponse shipmentImport(@RequestBody String shipment) {
        LOGGER.info("controller:/shipment/import data: {}", shipment);
        RestfulResponse result = new RestfulResponse<>(0, "成功", null);
        try {
            iItfImplogHeaderService.otmShipmentImport(shipment);
            return result;
        } catch (Exception e) {
            result.setCode(-1);
            result.setMessage(e.getMessage());
            return result;
        }
    }

    @RequestMapping(value = "/export", method = RequestMethod.POST)
    public RestfulResponse<String> shipmentExport(@RequestBody String shipment) {
        LOGGER.info("controller:/shipment/export data: {}", shipment);
        RestfulResponse<String> result = new RestfulResponse<>(0, "成功", null);
        try {
            //发送 POST 请求
            String sr = HttpRequest.sendPost("http://222.126.229.158:7778/GC3/glog.integration.servlet.WMServlet", shipment);
            LOGGER.info("export result:{}", sr);
            result.setData(sr);
            return result;
        } catch (Exception e) {
            result.setCode(-1);
            result.setMessage(e.getMessage());
            return result;
        }
    }

    @RequestMapping(value = "/result", method = RequestMethod.POST)
    public RestfulResponse exportResult(@RequestBody String resultXml) {
        LOGGER.info("controller:/shipment/result data: {}", resultXml);
        RestfulResponse result = new RestfulResponse<>(0, "成功", null);
        try {
            ItfImplogHeader itfImplogHeader = new ItfImplogHeader();
            itfImplogHeader.setId(snowFlakeId.nextId());
            itfImplogHeader.setType("OTM回调");
            itfImplogHeader.setDataContent(resultXml);
            iItfImplogHeaderService.insert(itfImplogHeader);
            LOGGER.info(resultXml);
            return result;
        } catch (Exception e) {
            result.setCode(-1);
            result.setMessage(e.getMessage());
            return result;
        }
    }

    /**
     * 统一从integration接收运单指令
     */
    @PostMapping(value = "/recvShipment")
    public RestfulResponse recvShipment(@RequestBody ShipmentDTO shipmentDTO) {
        LOGGER.info("controller:/shipment/recvShipment data: {}", shipmentDTO);
        RestfulResponse result = new RestfulResponse<>(0, "成功", null);
        try {

            //记录指令已接收到日志系统
            addSysLogs(shipmentDTO,2, 1);

//            iItfImplogHeaderService.updateShipmentOTM(shipmentDTO);
            importShipment.importOTMShipment(shipmentDTO);//更新OTM指令，重构接口方法

            //记录指令已处理到日志系统
            addSysLogs(shipmentDTO,3, 1);

        } catch (BaseException e) {
            LOGGER.error("controller:/shipment/recvShipment BaseException:{}", e.getMessage());
            result.setCode(-1);
            result.setMessage(e.getMessage());
            addSysLogs(shipmentDTO,3, 0);
        } catch (Exception e) {
            LOGGER.error("controller:/shipment/recvShipment error:{}", e.getMessage());
            result.setCode(-1);
            result.setMessage(e.getMessage());
            addSysLogs(shipmentDTO,3, 0);
        }

        return result;
    }

    /**
     * 添加日志记录到日志系统
     */
    public void addSysLogs(ShipmentDTO shipmentDTO, Integer dataStatus, Integer isSuc) {
        new Thread(() -> {
            try {
                if (Objects.nonNull(shipmentDTO)) {
                    String tableIdx = RedisLogTypeEnum.SHIPMENT.getCode();
                    String sourceSystem = SystemEnum.INTEGRATION.getCode();
                    String targetSystem = SystemEnum.WMS.getCode();
                    String uri = "/shipment/recvShipment";
                    // 来源、目标系统表示
                    // 目标API标示
                    String key = sourceSystem + "_" + targetSystem;
                    String fKey = uri + SystemEnum.UNDERLINE.getCode() + shipmentDTO.getShipmentId() + SystemEnum.UNDERLINE.getCode() + shipmentDTO.getSenderTransmissionNo() + SystemEnum.UNDERLINE.getCode() + dataStatus;
                    String dtoJson = JSONUtil.toJsonStr(shipmentDTO);
                    // 业务相关实体类
                    LogDataPo logDataPo = new LogDataPo(sourceSystem, targetSystem, uri, shipmentDTO.getShipmentId(), String.valueOf(shipmentDTO.getSenderTransmissionNo()), dtoJson, isSuc, "", 0, 0, dataStatus);
                    SysLogDataPo sysLogDataPo = new SysLogDataPo(tableIdx, JSONUtil.toJsonStr(logDataPo));
                    SysLogUtil.addSysLogs(key, fKey, sysLogDataPo, Boolean.valueOf(properties.getLogRedisIsTest()));
                }
            } catch (Exception e) {
                LOGGER.error("指令下发，添加日志异常" + e.getMessage());
            }
        }).start();
    }

    /**
     * 统一从integration接收修改运单信息
     */
    @PostMapping(value = "/updateReleaseInfo")
    public RestfulResponse updateReleaseInfo (@RequestBody ReleaseDTO releaseDTOs) {
        LOGGER.info("controller:/shipment/updateReleaseInfo data: {}", releaseDTOs);
        RestfulResponse result = new RestfulResponse<>(0, "成功", null);
        importShipment.updateReleaseInfo(releaseDTOs);
        return result;
    }

    /**
     * lspm(运力平台)查询运单状态
     */
    @PostMapping(value = "/queryShipmentStatus")
    public RestfulResponse<List<OtmOrderRelease>> queryShipmentStatus(@RequestBody List<Map<String,String>> queryParam) {
        LOGGER.info("controller:/shipment/queryShipmentStatus data: {}", queryParam);
        RestfulResponse<List<OtmOrderRelease>> result = new RestfulResponse<>(0, "成功", null);
        try {
            List<OtmOrderRelease> shipmentStatus = iOtmShipmentService.queryShipmentStatus(queryParam);
            result.setData(shipmentStatus);
        } catch (BaseException e) {
            LOGGER.error("controller:/shipment/queryShipmentStatus BaseException:{}", e);
            result.setCode(-1);
            result.setMessage(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("controller:/shipment/queryShipmentStatus error:{}", e);
            result.setCode(-1);
            result.setMessage(e.getMessage());
        }

        return result;
    }


    /**
     * 发运回传数据重新推送
     */
    @PostMapping("/queryPushShipmentOtm")
    public RestfulResponse<Page<OtmReleaseOtmDTO>> queryPushShipmentOtm(@RequestBody Page<OtmReleaseOtmDTO> page) {
        RestfulResponse<Page<OtmReleaseOtmDTO>> restfulResponse = new RestfulResponse<>(0, "success", null);
        Page<OtmReleaseOtmDTO> data = iOtmShipmentService.queryPushShipmentOtm(page);
        restfulResponse.setData(data);
        return restfulResponse;
    }


    /**
     * 发运回传数据重新推送
     */
    @PostMapping("/pushShipmentOtm")
    public RestfulResponse<String> pushShipmentOtm(@RequestBody Map<String,String> param) {
        RestfulResponse<String> restfulResponse = new RestfulResponse<>(0, "success", null);
        iOtmShipmentService.pushShipmentOtm(param);
        return restfulResponse;
    }

    /**
     * integration查询指令是否下发
     */
    @PostMapping("/queryShipmentInfo")
    public RestfulResponse<List<String>> queryShipmentInfo(@RequestBody List<String> param) {
        RestfulResponse<List<String>> restfulResponse = new RestfulResponse<>(0, "success", null);
        List<String> list = iOtmShipmentService.queryShipmentInfo(param);
        restfulResponse.setData(list);
        return restfulResponse;
    }

    /**
     * integration查询指令是否下发
     */
    @PostMapping("/getShipOrderItemCount")
    public RestfulResponse<List<ShipmentInfo>> getShipOrderItemCount(@RequestBody List<ShipmentInfo> page) {
        RestfulResponse<List<ShipmentInfo>> restfulResponse = new RestfulResponse<>(0, "success", null);
        List<ShipmentInfo> list = iOtmShipmentService.getShipOrderItemCount(page);
        restfulResponse.setData(list);
        return restfulResponse;
    }

    /**
     * OTM推送发运时间至wms
     */
    @PostMapping("/otmShipDateToWms")
    public RestfulResponse<String> otmShipDateToWms (@RequestBody List<OtmUpdateShipWmsDate> param) {
        RestfulResponse<String> restfulResponse = new RestfulResponse<>(0, "success", null);
        iOtmShipmentService.otmShipDateToWms(param);
        return restfulResponse;
    }

}
